<template>
  <div
    class="div-editable"
    contenteditable="true"
    v-html="innerText"
    @input="changeText"
    @focus="isChange = false"
    @blur="blurFunc"
    ref="input"
    v-on:keyup.ctrl.enter="$emit('send')"
  ></div>
</template>

<script>
export default {
  name: 'DivEditable',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      innerText: this.value,
      isChange: true
    }
  },
  watch: {
    value(newVal) {
      if (newVal === '' || newVal === null) {
        this.$refs.input.innerHTML = ''
      }
      if (this.isChange) {
        this.innerText = this.value
      }
    }
  },
  // 解决betterscroll回阻止原生click事件导致输入框点击聊天界面后不能失去焦点
  mounted() {
    // window.document.body.addEventListener('click', this.manualBlur)
    // window.document.body.addEventListener('top', this.manualBlur)
    // window.document.body.addEventListener('touchstart', this.manualBlur)
  },
  destroyed() {
    // window.document.body.removeEventListener('click', this.manualBlur)
    // window.document.body.removeEventListener('top', this.manualBlur)
    // window.document.body.removeEventListener('touchstart', this.manualBlur)
  },
  methods: {
    changeText() {
      this.$emit('input', this.$el.innerHTML)
    },
    blurFunc() {
      console.log('失去焦点')
      this.isChange = true
      this.$emit('blur')
    },
    focus() {
      this.$refs.input.focus()
      this.keepLastIndex(this.$refs.input)
    },
    manualBlur(e) {
      if (e.target !== this.$refs.input) {
        setTimeout(() => {
          this.$refs.input.blur()
        }, 0)
      }
    },
    keepLastIndex(element) {
      if (window.getSelection) {
        // ie11 10 9 ff safari
        element.focus() // 解决ff不获取焦点无法定位问题
        const range = window.getSelection() // 创建range
        range.selectAllChildren(element) // range 选择element下所有子内容
        range.collapseToEnd() // 光标移至最后
      } else if (document.selection) {
        // ie10 9 8 7 6 5
        const range = document.selection.createRange() // 创建选择对象
        range.moveToElementText(element) // range定位到element
        range.collapse(false) // 光标移至最后
        range.select()
      }
    },
    send() {
      console.log('eeee----send')
    }
  }
}
</script>

<style lang="scss" scoped>
.div-editable {
  caret-color:$green
}
</style>
